package com.bytedy.sboot.support;

import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import com.bytedy.sboot.support.dto.RespEntity;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import java.lang.Exception;


@Component
@Slf4j
public class CustomHandlerExceptionResolver extends ExceptionHandlerExceptionResolver implements WebMvcRegistrations {

    @Override
    protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response,
            HandlerMethod handlerMethod, Exception exception) {
        // return super.doResolveHandlerMethodException(request, response,
        // handlerMethod, exception);
        log.info("the request doResolveException: {}", exception.getMessage());
        return doProcess(request, response, handlerMethod, exception);
    }

    private ModelAndView doProcess(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        // Locale locale = RequestContextUtils.getLocale(request);
        try {
            if (!response.isCommitted()) {
                response.setContentType("text/html;charset=utf-8");
                request.setCharacterEncoding("utf-8");
                // ResultWriter.writeResp(response, ex.getMessage());
                ResultWriter.writeResp(response, RespEntity.fail(ex.getMessage()));
            } else {
                // 超时或者网络中断引起的异常, 仅仅打印警告;
                log.error(ex.getMessage(), ex);
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        return new ModelAndView();
    }

    @Override
    public ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() {
        return new CustomHandlerExceptionResolver();
    }
}
